﻿using System.Linq;
using System.Web.Mvc;

namespace MagicSauce.Filters
{
    public class ShowValidationErrors : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            LoadModelErrors(filterContext.Controller.ControllerContext);
            base.OnActionExecuting(filterContext);
        }


        protected void LoadModelErrors(ControllerContext context)
        {
            ModelStateDictionary dict = context.Controller.TempData["_modelState"] as ModelStateDictionary ?? null;

            if (dict != null)
            {
                Controller control = context.Controller as Controller;
                dict.ToList().ForEach(x => control.ModelState.Add(x.Key, x.Value));
            }
        }

    }

}
